﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Configuration;

namespace BlogHunterService
{
    public partial class BlogHunterService : ServiceBase
    {
        private static readonly string WIN_SERVICE_NAME = "BlogHunter Windows Service";
        private static readonly string WIN_SERVICE_TIME_INTERVAL = ConfigurationSettings.AppSettings["ServiceTimeInterval"];

        private Timer serviceTimer;
        BlogHunterApp app;
        private int period;
        private object state;

        public BlogHunterService()
        {
            this.ServiceName = WIN_SERVICE_NAME;
            this.EventLog.Source = WIN_SERVICE_NAME;
            this.EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            //  type of event. Set to true if you need it, false otherwise.
            this.CanHandlePowerEvent = true;
            this.CanHandleSessionChangeEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;

            if (!EventLog.SourceExists(WIN_SERVICE_NAME))
                EventLog.CreateEventSource(WIN_SERVICE_NAME, "Application");

            app = new BlogHunterApp();
        }

        protected override void OnStart(string[] args)
        {
            period = 30;

            if (!String.IsNullOrEmpty(WIN_SERVICE_TIME_INTERVAL))
                Int32.TryParse(WIN_SERVICE_TIME_INTERVAL.Trim(), out period);

            period = period * 60 * 1000;//Unit: One Minute

            serviceTimer = new Timer(new TimerCallback(TimerCallbackMethod), state, 0, period);
        }

        protected override void OnStop()
        {
            serviceTimer.Change(Timeout.Infinite, Timeout.Infinite);
        }

        public void TimerCallbackMethod(object obj)
        {
            app.AppRun();
        }
    }
}
